﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;
namespace HF.WorkFlow.Template
{
    /// <summary>
    /// 数据访问类WorkFlowData。
    /// </summary>
    public class WorkFlowTemplate
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "WorkFlowId", "FlowCaption", "WFClassId", "Version", "Status", "CreateUserId", 
                                         "CreateDateTime", "IsSignOut", "SignOutUserId", "Description","MgrUrl" };
        private string tableName = "HF_WorkFlow";
        private string keyField = "WorkFlowId";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(WorkFlowEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@WorkFlowId", entity.WorkFlowId, typeof(string));
            sqlDataItem.AppendParameter("@FlowCaption", entity.FlowCaption, typeof(string));
            sqlDataItem.AppendParameter("@WFClassId", entity.WFClassId, typeof(string));
            sqlDataItem.AppendParameter("@Version", entity.Version, typeof(string));
            sqlDataItem.AppendParameter("@Status", entity.Status, typeof(string));
            sqlDataItem.AppendParameter("@CreateUserId", entity.CreateUserId, typeof(string));
            sqlDataItem.AppendParameter("@CreateDateTime", entity.CreateDateTime, typeof(DateTime));
            sqlDataItem.AppendParameter("@IsSignOut", entity.IsSignOut, typeof(string));
            sqlDataItem.AppendParameter("@SignOutUserId", entity.SignOutUserId, typeof(string));
            sqlDataItem.AppendParameter("@Description", entity.Description, typeof(string));
            sqlDataItem.AppendParameter("@MgrUrl", entity.MgrUrl, typeof(string));
        }
        public WorkTaskViewEntity GetWorkTaskViewEntity(DataRow dr)
        {
            WorkTaskViewEntity entity = new WorkTaskViewEntity();
            entity.WFClassId = dr["WFClassId"].ToString();
            entity.Caption = dr["Caption"].ToString();
            entity.FatherId = dr["FatherId"].ToString();
            entity.WorkFlowId = dr["WorkFlowId"].ToString();
            entity.FlowCaption = dr["FlowCaption"].ToString();
            entity.WorkTaskId = dr["WorkTaskId"].ToString();
            entity.TaskCaption = dr["WFClassId"].ToString();
            string value = dr["classlevel"].ToString();
            if (string.IsNullOrEmpty(value) == false)
            {
                entity.classlevel = Convert.ToInt16(value);
            }
            entity.mgrurl = dr["mgrurl"].ToString();
            entity.clmgrurl = dr["clmgrurl"].ToString();
            return entity;
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public WorkFlowEntity GetWorkFlowEntity(DataRow dr)
		{
			WorkFlowEntity  entity=new WorkFlowEntity();
			string value="";
			entity.WorkFlowId=dr["WorkFlowId"].ToString();
			entity.FlowCaption=dr["FlowCaption"].ToString();
			entity.WFClassId=dr["WFClassId"].ToString();
			entity.Version=dr["Version"].ToString();
			entity.Status=dr["Status"].ToString();
			entity.CreateUserId=dr["CreateUserId"].ToString();
			value=dr["CreateDateTime"].ToString();
			if(string.IsNullOrEmpty(value)==false)
			{
				entity.CreateDateTime=Convert.ToDateTime(value);
			}
			entity.IsSignOut=dr["IsSignOut"].ToString();
			entity.SignOutUserId=dr["SignOutUserId"].ToString();
			entity.Description=dr["Description"].ToString();
            entity.MgrUrl = dr["MgrUrl"].ToString();
			return entity;
		}

        #endregion

        #region  构造函数
        public WorkFlowTemplate()
        { }
        public static WorkFlowTemplate GetInstance()
        {
            return new WorkFlowTemplate();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(WorkFlowEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(WorkFlowEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string workFlowId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, workFlowId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除流程信息，只删除流程主表
        /// </summary>
        /// <param name="workFlowId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string workFlowId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, workFlowId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="WorkFlowId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetWorkFlowTable(string workFlowId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, workFlowId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="workFlowId">主键Id</param>
        /// <returns>DataTable</returns>
        public WorkFlowEntity GetWorkFlowEntity(string workFlowId)
        {
            DataTable dt = GetWorkFlowTable(workFlowId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetWorkFlowEntity(dt.Rows[0]);
            }
            return null;
        }

        #endregion

        #region  扩展方法
        //此处添加扩展方法
        

        /// <summary>
        /// 获取可以启动的流程
        /// </summary>
        /// <param name="FatherClassId">UserId</param>
        /// <returns>可启动的流程Table</returns>
        public  DataTable GetAllowsStartWorkFlows(string userId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_GetAllowsStartWorkFlowsPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 删除流程模板,删除流程相关的所有信息
        /// </summary>
        /// <param name="workFlowId">workFlowId</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteWorkFlowTemplate(string workFlowId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_DeleteWorkflow";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@WorkflowId", workFlowId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
                return true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得工作流模板信息
        /// </summary>
        /// <param name="caption">流程模板名称,模糊查询</param>
        /// <returns>DataTable</returns>
        public  DataTable GetWorkFlowsLikeCaption(string caption)
        {

            string tmpStr = "select * from HF_WorkFlow where FlowCaption like @workflowCaption";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpStr;
                sqlItem.AppendParameter("@workflowCaption", "%" + caption + "%");
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得工作流模板信息
        /// </summary>
        /// <param name="caption">流程模板名称,模糊查询</param>
        /// <returns>DataTable</returns>
        public List<WorkFlowEntity> GetWorkFlowEntitysLikeCaption(string caption)
        {
            List<WorkFlowEntity> result = new List<WorkFlowEntity>();
            DataTable dt = GetWorkFlowsLikeCaption(caption);
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    WorkFlowEntity entity = GetWorkFlowEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得流程分类下的所有流程列表
        /// </summary>
        /// <param name="classId">流程分类Id</param>
        /// <returns>流程列表</returns>
        public DataTable GetWorkFlowsByClassId(string classId)
        {
            try
            {
                string tmpStr = "select * from HF_WorkFlow where WFClassId=@classId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpStr;
                sqlItem.AppendParameter("@classId", classId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得流程分类下的所有流程列表
        /// </summary>
        /// <param name="classId">流程分类Id</param>
        /// <returns>流程列表Entitys</returns>
        public List<WorkFlowEntity> GetWorkFlowEntitysByClassId(string classId)
        {
            List<WorkFlowEntity> result = new List<WorkFlowEntity>();
            DataTable dt = GetWorkFlowsByClassId(classId);
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    WorkFlowEntity entity = GetWorkFlowEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设置工作流模板状态。status=1 启用，status=0 禁用
        /// </summary>
        /// <param name="workflowId">流程模板Id</param>
        /// <returns></returns>
        public  int SetWorkFlowStatus(string workFlowId, string status)
        {
            try
            {
                string tmpSql = "update HF_WorkFlow set status=@status where WorkFlowId=@workflowId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@workflowId", workFlowId);
                sqlItem.AppendParameter("@status", status);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设置流程分类
        /// </summary>
        /// <param name="workflowId">流程模板Id</param>
        /// <param name="wfclassid">流程分类Id</param>
        /// <returns></returns>
        public  bool SetWorkFlowClass(string workFlowId, string wfClassId)
        {
            try
            {
                string tmpSql = "update HF_workflow set wfclassId=@wfclassid where WorkFlowId=@workflowId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@workflowId", workFlowId);
                sqlItem.AppendParameter("@wfclassid", wfClassId);
                ClientDBAgent agent = new ClientDBAgent();
                int i= agent.ExecuteNonQuery(sqlItem);
                return i>0;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #endregion
        /// <summary>
        /// 获取可以启动的流程
        /// </summary>
        /// <param name="FatherClassId">UserId</param>
        /// <returns>可启动的流程Entitys</returns>
        public List<WorkTaskViewEntity> GetAllowsStartWorkFlowEntitys(string userId)
        {
            List<WorkTaskViewEntity> result = new List<WorkTaskViewEntity>();
            DataTable dt = GetAllowsStartWorkFlows(userId);
            foreach (DataRow dr in dt.Rows)
            {
                WorkTaskViewEntity entity = GetWorkTaskViewEntity(dr);
                result.Add(entity);
            }
            return result;
        }
        /// <summary>
        /// 查询流程类表
        /// </summary>
        /// <returns></returns>
        public DataTable SetHFWorkFlowClass()
        {
            try
            {
                string tmpSql = "select * from HF_WorkFlowClass where ClassLevel='1'";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                ClientDBAgent agent = new ClientDBAgent();
                DataTable dt = agent.ExecuteDataTable(sqlItem);
                return dt.Rows.Count > 0 ? dt : null;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取流程信息
        /// </summary>
        /// <returns></returns>
        public DataTable GetWorkFlow()
        {
            try
            {
                string tmpStr = "select * from HF_WorkFlow";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpStr;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

